<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="ordCode">
        <el-input
            v-model="queryParams.ordCode"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="ordDesc">
        <el-input
            v-model="queryParams.ordDesc"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="价格区间">
        <el-row>
          <el-col :span="11">
            <el-input-number v-model="queryParams.minActualAmount" :controls="false"
                             placeholder="最小价格"></el-input-number>
          </el-col>
          <el-col :span="2">-</el-col>
          <el-col :span="11">
            <el-input-number v-model="queryParams.maxActualAmount" :controls="false"
                             placeholder="最大价格"></el-input-number>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="商家名称" prop="merName" v-if="useUserStore().userType !== '2'">
        <el-input
            v-model="queryParams.merName"
            placeholder="请输入商家名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺名称" prop="shopName">
        <el-input
            v-model="queryParams.shopName"
            placeholder="请输入店铺名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经销商" prop="parName" v-if="useUserStore().userType !== '2'">
        <el-input
            v-model="queryParams.parName"
            placeholder="请输入经销商"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
              v-for="dict in ty_order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              v-show="dict.value !== '10' && dict.value !== '11'"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:tord:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单编号" align="center" prop="ordCode"/>
      <el-table-column label="用户名称" align="center" prop="userName"/>
      <el-table-column label="商品名称" align="center" prop="ordDesc"/>
      <el-table-column label="订单时间" width="180" align="center" prop="createTime"/>
      <el-table-column label="支付费用" align="center" prop="actualAmount"/>
      <el-table-column label="支付单号" width="250" align="center" prop="ext1"/>
      <el-table-column label="支付方式" align="center" prop="payType">
        <template #default="scope">
          <dict-tag :options="t_pay_type" :value="scope.row.payType"/>
        </template>
      </el-table-column>
      <el-table-column label="归属商家" align="center" prop="merName" v-if="useUserStore().userType !== '2'" />
      <el-table-column label="归属店铺" align="center" prop="shopName"/>
      <el-table-column label="平台佣金" align="center" prop="platAmount"/>
      <el-table-column label="经销商佣金" align="center" prop="parAmount"/>
      <el-table-column label="经销商" align="center" prop="parName"/>
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="ty_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary"
                     :class="{'but-disabled': userStore.isRead === 1 || (userStore.isRead === 0 && !(scope.row.status === '1' || (scope.row.status === '2' && scope.row.actualAmount === 0)))}"
                     icon="RemoveFilled" @click="handleCancel(scope.row)" v-hasPermi="['system:tord:cancel']">取消
          </el-button>
          <el-button link type="primary"
                     :class="{'but-disabled': userStore.isRead === 1 || (userStore.isRead === 0 && !(scope.row.status === '2' && scope.row.actualAmount > 0))}"
                     icon="RemoveFilled" @click="handleRefund(scope.row)" v-hasPermi="['system:tord:refund']">退款
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     :class="{'but-disabled': userStore.isRead === 1 || (userStore.isRead === 0 && !(scope.row.status === '7' || scope.row.status === '4' || scope.row.status === '3' || scope.row.status === '5' || scope.row.status === '6' || scope.row.status === '9'))}"
                     v-hasPermi="['system:tord:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改订单列表对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="tordRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单编号" prop="ordCode">
              <el-input v-model="form.ordCode" placeholder="请输入订单编号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单描述" prop="ordDesc">
              <el-input v-model="form.ordDesc" placeholder="请输入订单描述"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="外部订单号" prop="outOrdCode">
              <el-input v-model="form.outOrdCode" placeholder="请输入外部订单号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户id" prop="userId">
              <el-input v-model="form.userId" placeholder="请输入用户id"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺ID" prop="shopId">
              <el-input v-model="form.shopId" placeholder="请输入店铺ID"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺名称" prop="shopName">
              <el-input v-model="form.shopName" placeholder="请输入店铺名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商家ID" prop="merId">
              <el-input v-model="form.merId" placeholder="请输入商家ID"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商家名称" prop="merName">
              <el-input v-model="form.merName" placeholder="请输入商家名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入订单金额"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="优惠金额" prop="disAmount">
              <el-input v-model="form.disAmount" placeholder="请输入优惠金额"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="实付金额" prop="actualAmount">
              <el-input v-model="form.actualAmount" placeholder="请输入实付金额"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="支付时间" prop="payTime">
              <el-date-picker clearable
                              v-model="form.payTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择支付时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="核销时间" prop="verifyTime">
              <el-date-picker clearable
                              v-model="form.verifyTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择核销时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="失效时间" prop="expTime">
              <el-date-picker clearable
                              v-model="form.expTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择失效时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in ty_order_status"
                    :key="dict.value"
                    :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态原因" prop="statusReason">
              <el-input v-model="form.statusReason" placeholder="请输入状态原因"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tord">
import {listTord, getTord, delTord, addTord, updateTord, cancelOrd, refundOrd, deleteOrd} from "@/api/system/tord";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore()
const {proxy} = getCurrentInstance();
const {ty_order_status,t_pay_type} = proxy.useDict('ty_order_status','t_pay_type');

const tordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    ordCode: undefined,
    ordDesc: undefined,
    type: undefined,
    outOrdCode: undefined,
    userId: undefined,
    userName: undefined,
    shopId: undefined,
    shopName: undefined,
    merId: undefined,
    merName: undefined,
    amount: undefined,
    disAmount: undefined,
    actualAmount: undefined,
    payTime: undefined,
    verifyTime: undefined,
    expTime: undefined,
    status: undefined,
    statusReason: undefined,
  },
  rules: {
    ordCode: [
      {required: true, message: "订单编号不能为空", trigger: "blur"}
    ],
    type: [
      {required: true, message: "订单类型不能为空", trigger: "change"}
    ],
    userId: [
      {required: true, message: "用户id不能为空", trigger: "blur"}
    ],
    shopId: [
      {required: true, message: "店铺ID不能为空", trigger: "blur"}
    ],
    merId: [
      {required: true, message: "商家ID不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "状态不能为空", trigger: "change"}
    ],
    state: [
      {required: true, message: "数据状态不能为空", trigger: "blur"}
    ],
    createTime: [
      {required: true, message: "创建时间不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询订单列表列表 */
function getList() {
  loading.value = true;
  listTord(queryParams.value).then(response => {
    tordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    ordId: undefined,
    ordCode: undefined,
    ordDesc: undefined,
    type: undefined,
    outOrdCode: undefined,
    userId: undefined,
    userName: undefined,
    shopId: undefined,
    shopName: undefined,
    merId: undefined,
    merName: undefined,
    amount: undefined,
    disAmount: undefined,
    actualAmount: undefined,
    payTime: undefined,
    verifyTime: undefined,
    expTime: undefined,
    parentOrdId: undefined,
    status: undefined,
    statusReason: undefined,
    ext1: undefined,
    ext2: undefined,
    ext3: undefined,
    state: undefined,
    createTime: undefined,
    creator: undefined,
    modifyTime: undefined,
    modifier: undefined
  };
  proxy.resetForm("tordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.ordId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单列表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _ordId = row.ordId || ids.value
  getTord(_ordId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单列表";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tordRef"].validate(valid => {
    if (valid) {
      if (form.value.ordId != null) {
        updateTord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

//取消按钮
function handleCancel(row) {
  proxy.$modal.confirm('是否确认取消？').then(function () {
    return cancelOrd({ordId: row.ordId, cancelReason: "后台管理取消"});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("取消成功");
  }).catch(() => {
  });
}

//退款按钮
function handleRefund(row) {
  proxy.$modal.confirm('是否确认退款？').then(function () {
    return refundOrd({ordId: row.ordId, refundReason: "后台管理退款"});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("退款成功，等待1-3分钟刷新列表");
  }).catch(() => {
  });
}


/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除订单？').then(function () {
    return deleteOrd({ordId: row.ordId, deleteReason: "后台管理退款"});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/tord/export', {
    ...queryParams.value
  }, `tord_${new Date().getTime()}.xlsx`)
}

getList();
</script>
